<template>
  <div>
    <div>
      <el-button @click="handleCreate" type="primary">新增供应商</el-button>
    </div>
    <div class="top-operate-default mar-t-20 mar-b-20">
      <div class="search-item">
        <label>搜索品牌：</label>
        <el-select v-model="keywordType" placeholder="请选择" style="width: 120px">
          <el-option
            v-for="item in keywordTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-input @keyup.enter.native="handleSearch" v-model="dataListQuery.keywordWord" placeholder="请输入搜索内容" style="width: 200px"></el-input>
        <label class="mar-l-20">供应商分类：</label>
        <el-select v-model="dataListQuery.categoryId">
          <el-option value="" label="全部"></el-option>
          <el-option
            v-for="item in supplierCategoryList"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId">
          </el-option>
        </el-select>
        <label class="mar-l-20">供应商状态：</label>
        <el-select v-model="dataListQuery.status">
          <el-option
            v-for="item in statuss"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <label class="mar-l-20">创建时间：</label>
        <el-date-picker v-model="datePicker"
                        type="daterange"
                        unlink-panels
                        range-separator="至"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']"
                        start-placeholder="创建开始时间"
                        end-placeholder="创建结束时间">
        </el-date-picker>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </el-button-group>
      </div>
    </div>

    <div class="mar-b-20">
      <el-button @click="batchUpdateStatus(0)">批量启用</el-button>
    </div>

    <!-- 内容列表 -->
    <div class="table-container">
      <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中" style="width: 100%" >
        <el-table-column width="45px" type="selection"/>
        <el-table-column label="供应商名称" width="230px">
          <div slot-scope="scope" class="name-bule">
            {{ scope.row.supplierName }}
          </div>
        </el-table-column>
        <template v-if="getVersionType() == 1 || getVersionType() == 4">
          <el-table-column label="操作员姓名" width="260px">
            <template slot-scope="scope">
              {{ scope.row.realName }}
              <br/>
              {{ scope.row.phone }}
            </template>
          </el-table-column>
          <el-table-column width="200px" label="角色">
            <template slot-scope="scope">
              供应商
            </template>
          </el-table-column>
          <el-table-column width="200px" label="分类" prop="supplierCategoryNames"></el-table-column>
          <el-table-column label="状态" prop="status">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 0">启用</span>
              <span v-if="scope.row.status == 1">禁用</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="商品数量" prop="goodsNum"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column width="140px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="medium" v-if="scope.row.status == 1" @click="updateStatus(scope.row,0)">启用</el-button>
            <el-button type="text" size="medium" v-if="scope.row.status == 0" @click="updateStatus(scope.row,1)">禁用</el-button>
            <el-button type="text" size="medium" v-if="scope.row.status == 1" @click="deleteVillage(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                      :current-page="dataListQuery.currentPage"
                      :page-sizes="[10, 20, 50, 100]" :page-size="dataListQuery.size"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total">
      </el-pagination>
    </div>

    <!--社区版供应商-->
    <el-dialog title="供应商编辑" :visible.sync="formVisible" :close-on-press-escape="true" width="650px">
      <el-form :model="entity" label-position="right" label-width="100px" style='width: 500px; margin-left:50px;'>
        <el-form-item label="供应商名称">
          <el-input v-model="entity.supplierName" placeholder="请输入供应商名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="doSave">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { pagingSupplier, deleteSupplier, saveSupplier, batchUpdateStatus, updateStatus } from '@/api/user/supplier'
  import { listSupplierCategory } from '@/api/user/supplierCategory'
  import { listEnterpeiseRole } from '@/api/system/role'

  export default {
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      }
    },
    data() {
      return {
        keywordType: 'supplierName',
        keywordTypes: [{
          value: 'supplierName',
          label: '供应商名称'
        }, {
          value: 'realName',
          label: '操作员姓名'
        }, {
          value: 'phone',
          label: '手机号'
        }],
        statuss: [{
          value: '',
          label: '全部'
        }, {
          value: '0',
          label: '已启用'
        }, {
          value: '1',
          label: '已禁用'
        }],
        entity: {
          supplierName: '',
          supplierId: '',
          enterpriseId: this.getEnterpriseId()
        },
        dataListQuery: {
          keywordWord: '',
          supplierName: '',
          realName: '',
          phone: '',
          enterpriseId: this.getEnterpriseId(),
          categoryId: '',
          status: '',
          startTime: '',
          endTime: '',
          currentPage: 1,
          size: 10
        },
        total: null,
        datePicker: [],
        dataList: [],
        // 供应商分类集合
        supplierCategoryList: [],
        subRoleList: [],
        listLoading: false,
        formVisible: false
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.initData()
        }
      }
    },
    // 初始化页面
    created() {
      this.initData()
      listEnterpeiseRole({ enterpriseId: this.getEnterpriseId(), supplierFlag: 1 }).then(response => {
        if (response.isError) return
        this.subRoleList = response.data
      })
      listSupplierCategory({ enterpriseId: this.getEnterpriseId() }).then(response => {
        if (response.isError) return
        this.supplierCategoryList = response.data
      })
    },
    mounted() {
    },
    methods: {
      // 初始数据
      initData() {
        this.listLoading = true
        const datePicker = this.datePicker
        if (this.$utils.isExist(datePicker) && datePicker.length > 0) {
          this.dataListQuery.startTime = datePicker[0]
          this.dataListQuery.endTime = datePicker[1]
        } else {
          this.dataListQuery.startTime = ''
          this.dataListQuery.endTime = ''
        }
        this.dataListQuery.supplierName = ''
        this.dataListQuery.realName = ''
        this.dataListQuery.phone = ''
        this.dataListQuery[this.keywordType] = this.dataListQuery.keywordWord
        pagingSupplier(this.dataListQuery).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 查询
      handleSearch() {
        this.dataListQuery.currentPage = 1
        this.initData()
      },
      // 重置事件
      resetSearch() {
        this.keywordType = 'supplierName'
        this.dataListQuery = {
          keywordWord: '',
          supplierName: '',
          realName: '',
          phone: '',
          enterpriseId: this.getEnterpriseId(),
          categoryId: '',
          status: '',
          startTime: '',
          endTime: '',
          currentPage: 1,
          size: 10
        }
        this.datePicker = []
        this.initData()
      },
      // 新增供应商事件
      handleCreate() {
        if (this.getVersionType() === '1' || this.getVersionType() === '4') {
          this.$router.push({ path: '/supplier/edit/index' })
        } else {
          this.resetEntity()
          this.formVisible = true
        }
      },
      // 批量启用
      batchUpdateStatus(status) {
        const multipleSelection = this.multipleSelection
        if (!multipleSelection || multipleSelection.length === 0) {
          this.$message({ type: 'error', message: '请先选择操作数据!' })
          return
        }
        const roleIds = []
        multipleSelection.forEach((e) => {
          roleIds.push(e.supplierId)
        })
        batchUpdateStatus(status, roleIds.join(',')).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '成功!' })
          this.initData()
        })
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 跳转商品管理
      clickGoodsNum(row) {
        this.$router.push({ path: '/goods/manager/index', query: { supplierId: row.supplierId }})
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.dataListQuery.size = val
        this.initData()
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.dataListQuery.currentPage = val
        this.initData()
      },
      // 重置表单
      resetEntity() {
        this.entity = {
          supplierName: '',
          supplierId: '',
          enterpriseId: this.getEnterpriseId()
        }
      },
      // 编辑
      handleUpdate(row) {
        if ((!this.subRoleList || this.subRoleList.length <= 0) && this.getVersionType() === 5) {
          this.$message.error('还未有角色，请先创建角色')
          return
        }
        if (this.getVersionType() === '1' || this.getVersionType() === '4') {
          this.$router.push({ path: '/supplier/edit/index', query: { supplierId: row.supplierId }
          })
        } else {
          this.resetEntity()
          Object.assign(this.entity, row)
          this.formVisible = true
        }
      },
      // 启用/禁用事件
      updateStatus(row, status) {
        updateStatus(status, row.supplierId).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '成功!' })
          this.initData()
        })
      },
      // 删除事件
      deleteVillage(row) {
        this.$confirm('此操作将删除该数据，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteSupplier(row.supplierId).then(response => {
            if (response.isError) return
            this.initData()
          })
        }).catch(() => {})
      },
      // 保存事件
      doSave() {
        if (!this.entity.supplierName) {
          this.$message.error('供应商名称不能为空')
          return
        }
        saveSupplier(this.entity).then(response => {
          if (response.isError) return
          this.formVisible = false
          this.$message({ type: 'success', message: '保存成功!' })
          this.initData()
        })
      }
    }
  }
</script>

<style lang="less" scoped>
.name-bule{
  color: #396cd0;
}
</style>
